
//妙购一卡通JSON数组
var ecard = [	
             	{"ServiceType":1,"OrderType":"","TxnType":0,"OrderId":"","OrderIdName":"","TransAmt":0,"SpecialAmt":0,"CAIC":"","PIN":"","UseCoupon":0,"Postage":0,"CreditsFlag":0,"RFU":"","SellorCardNo":"","CardNo":"","PhoneNo":"","Token":"","ValidCode":"","NotifyUrl":"","ReturnUrl":"","NoticeId":"","NoticeTime":"","BZ":"","RequestType":4150},
                { "CAIC": "", "RequestType": 34952,"PinFlag":1,"PIN":""},
                { "OrderId": "", "RequestType": 39169, "OrderType": "","OrderName":"","CAIC":"","TransAmt":"","UUID":"","isCoupon":"","specialAmt":"","BZ":"" },
                { "RFU": "", "RequestType": 37008 },//读卡信息
                { "RequestType": 34953, "TransAmt": 0.0, "CAIC": "", "CATI": "", "PIN": "", "TransType": 1 },//验证卡信息
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "UseCoupon": 1, "Postage": 0.0, "PostagePayment": 0, "CreditsFlag": 1, "RFU": "", "RequestType": 4149, 'BatchNo': '', 'TxnChanne': '', 'OPR_ID': '', 'ACQ_INST_ID': '', 'ACQ_TSN': '', 'ISSUER_ID': '','MCHNT_DSP':'' },       //订购预授权
                {'OrderId': '', 'TransAmt': 0.0, 'CAIC': '', 'TN': '', 'CATI': '', 'ApprovalCode': '', 'PIN': '', 'PRRN': '', 'PDate': '', 'RFU': '', 'RequestType': 12341 },                                //订购预授权取消
                {'OrderId': '', 'TransAmt': 0.0, 'CAIC': '', 'TN': '', 'CATI': '', 'PIN': '', 'UseCoupon': 1, 'Postage': 0.0, 'PostagePayment': 0, 'CreditsFlag': 1, 'RFU': '', 'RequestType': 21249 },      //订购预授权冲正
                {'OrderId': '', 'TransAmt': 0.0, 'CAIC': '', 'TN': '', 'CATI': '', 'ApprovalCode': '', 'OprFlag': 2, 'OrderDate': '', 'PIN': '', 'PRRN': '', 'PDate': '', 'RFU': '', 'RequestType': 4165 }, //订购预授权确认
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "OprFlag": "", "PinData": "", "NameFlag": "N", "Name": "", "IdType": "", "IdNum": "", "UF": 0, "RFU": "", "RequestType": 28933 },  //修改/重置PIN
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "UF": 0, "RFU": "", "RequestType": 29445 }, //PIN限额
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PinFlag": "Y", "PinData": "", "NameFlag": "Y", "Name": "", "IdType": 1, "IdNum": "", "Phone": "", "Email": "", "PostAddr": "", "PostCode": "", "UserId": "", "LoginId": "", "PinCheckAmt": 0.0, "BalNotice": 0.0, "RFU": "", "RequestType": 28677 }, //账户开通
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "PAN": "", "PinFlag": "Y", "PinData": "", "RFU": "", "RequestType": 28709 }, //附卡绑定主卡账户
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "CardNo": "", "CardStatus": "Y", "UF": 0, "RFU": "", "RequestType": 29717 }, //修改客户卡信息
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "IfReadCard": "Y", "CardNo": "", "LF": "Y", "UF": 0, "RFU": "", "RequestType": 29749 }, //验证账户信息
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "AttachCardNum": "", "UF": 0, "RFU": "", "RequestType": 28725 }, // 附卡解除绑定
                {"CAIC": "", "TN": "", "CATI": "", "RFU": "", "RequestType": 25093 }, //更新终端主密钥
                {"CAIC": "", "TN": "", "CATI": "", "RFU": "", "RequestType": 25125 }, //更新终端工作密钥
                {"SrvIp": "127.0.0.1", "SrvPort": 0, "SrvIpBak": "127.0.0.1", "SrvPortBak": 0, "COMX": "", "RFU": "", "RequestType": 32896 }, //通讯参数设置
                {"RFU": "", "RequestType": 32768 }, //获取设备信息
                {"SrvDomainName": "", "SrvPort": 0, "RFU": "", "RequestType": 32897 }, //设置清算中心域名
                {"RFU": "0", "RequestType": 39321 }, //清算线路测试,
                {"UptIp": "112.65.184.46", "UptPort": 41000, "RFU": "", "RequestType": 33280 }, //查询妙购服务程序版本
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "OrderId": "", "ItemId": "", "CreditsRFU": "", "Postage": 0.0, "PostagePayment": 0, "RFU": "", "RequestType": 4613 }, //积分消费
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "OrderId": "", "ItemId": "", "CreditsRFU": "", "Postage": 0.0, "PostagePayment": 0, "RFU": "", "RequestType": 20513 }, //积分消费冲正
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "OrderId_Origin": "", "RRN_Origin": "", "RFU": "", "RequestType": 12805 }, //积分消费撤销
                {"TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "OrderId_Origin": "", "RRN_Origin": "", "ApprovalCode": "", "AffirmDate": "", "RFU": "", "RequestType": 4629 }, //积分消费确认
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankFlag": "Y", "BankAccNo": "", "CardHolderName": "", "UF": 0, "RFU": "", "RequestType": 5173, "CallFlag": 0, "ExpiredDate": "", "Cvv2": "", "ValidCode": "", "ExternalRefNumber": "", "Token": "","StorablePan":"" }, //银行代扣请求
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankFlag": "Y", "BankAccNo": "", "CardHolderName": "", "UF": 0, "RFU": "", "RequestType": 5189 }, //银行代扣查询
                {"OrderId": "", "TransAmt": "", "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankAccNo": "", "Mobile": "", "BankCode": "", "Rsvd": "", "BankProvince": "", "BankCity": "", "BankName": "", "AccType": "", "ExpireDate": "", "CVV": "", "TxnPIN": "", "PinCheckAmt": "", "BalNotice": "", "ExtNo": "", "AuthFlag": "Y", "Name": "", "IdType": "", "IdNo": "", "AppendInfoFlag": "N", "Phone": "", "Email": "", "Address": "", "PostCode": "", "Length": "", "AppendInfo": "" , "RequestType": 33029 }, //银行代扣签约开户（申请）
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankAccNo": "", "Mobile": "", "BankCode": "", "Rsvd": "", "BankProvince": "", "BankCity": "", "BankName": "", "AccType": "", "ExpireDate": "", "CVV": "", "Length": "0", "AppendInfo": "", "UF": "0", "RFU": "", "ChannelNo": "", "AuthType": "", "CheckType": "", "CheckAmt": "", "RequestType": 33045 }, //银行代扣签约（已开户）
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankFlag": "N", "BankAccNo": "", "CardHolderName": "", "UF": 0, "RFU": "", "RequestType": 33061 }, //银行代扣签约解除
                {"OrderId": "", "TransAmt": 0.0, "CAIC": "", "TN": "", "CATI": "", "PIN": "", "BankAccNo": "", "UF": 0, "RFU": "", "RequestType": 33077 }, //银行代扣签约查询
                {"UptIp": "", "UptPort": 0, "ReqVer": 0, "PktSize": 0, "SHA1": "", "FileName": "", "LocalPath": "", "RFU": "", "RequestType": 33281 }, //下载妙购服务程序更新包（8201）
                {"UptIp": "", "UptPort": 0, "RFU": "", "RequestType": 33024 }, //查询读写器固件最新版本（8100）
                {"UptIp": "", "UptPort": 0, "ChipType": 255, "ReqVer": "", "AppSize": 0, "SHA1": "", "FileName": "", "RFU": "", "RequestType": 33025 }, //更新指令1（8101）
                {"RFU": "", "RequestType": 33026 }, //更新指令2（8102）
                {"RFU": "", "RequestType": 33027},//更新指令3（8103）
                {"TransAmt":0,"CAIC":"","TN":"","CATI":"","PIN":"","AccNo":"","PinCheckAmt":0,"BalNotice":0,"SCMA":0,"SRMA":0,"DMCN":0,"DMRN":0,"DMCCA":0,"DMRCA":0,"RFU":"","RequestType":29701},//修改帐户信息
                {"TransAmt":0,"CAIC":"","TN":"","CATI":"","PIN":"","LF": "Y", "UF": 0,"RFU":"","RequestType":29765},//客户登录
                {"TransAmt":0,"CAIC":"","TN":"","CATI":"","PIN":"","AccNo":"","ClientType":"","ClientName":"","IdType":"","IdNo":"","ClientRank":"","Phone": "","Email": "","LoginName": "","NickName": "","LoginPwd":"","Sex":"","HomePhone":"","OfficePhone":"","OtherPhone":"","Addr1":"","Postcode1":"","Addr2":"","Postcode2":"","ClientStatus":"0","RequestType":29781}//修改客户信息
                
                
            ];
/**
* 获取json数据模板
* @param req 接口类型
* @returns 返回json数据模板
*/
function getEcardToneJson(req) {
  var e = null;
  for (var i = 0; i < ecard.length; i++) {
      if (ecard[i].RequestType == req) {
          e = ecard[i];
          break;
      }
  }
  return e;
}
/**
* 调用ActiveX
* @param pCBFuncName 回调函数名称  
* @param pJson Json数据
*/
function MiugoActiveXExc(pCBFuncName,pJson){
	var miguoActiveX = document.getElementById("Miugo");
	if(miguoActiveX != null){
		miguoActiveX.CallbackFunc = pCBFuncName;
		miguoActiveX.Trade(pJson);
	}
}




/**
* 判断是否为空
* @param pStr  要检查的数据
* @returns {Boolean} 返回是否为空
*/
function IsEmpty(pStr){
  return ((pStr==null) || (pStr.length==0) );
} 
/**
* 判断字符串是不是数字（可以为负数，小数）
* @param str
* @returns 返回判断结果
*/
function IsNumber(pStr)
{
  if (IsEmpty(pStr))
      return true;
  if (isNaN(pStr))
      return false;
  return true; 
} 
/**
* 格式化字符串，向左补0
* @param str 
* @param lenght
* @returns
*/
function PadLeftZero(str, lenght) {
  if (str.length >= lenght)
      return str;
  else
      return PadLeftZero("0" + str,lenght);
}

/**
*验证身份证号
*@param cardId
*@returns 返回判断结果
*/
function isCardId(cardId){
	var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};
	var iSum=0 ;
	if(!/^\d{17}(\d|x)$/i.test(cardId)) return false; 
	cardId=cardId.replace(/x$/i,"a"); 
	if(aCity[parseInt(cardId.substr(0,2))]==null) return false; 
	sBirthday=cardId.substr(6,4)+"-"+Number(cardId.substr(10,2))+"-"+Number(cardId.substr(12,2)); 
	var d=new Date(sBirthday.replace(/-/g,"/")) ;
	if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return false; 
	for(var i = 17;i>=0;i--) iSum += (Math.pow(2,i) % 11) * parseInt(cardId.charAt(17 - i),11) ;
	if(iSum%11!=1) return false; 
	return true;//aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女") 
}

/**
*验证身份证号
*@param className
*@returns 返回判断结果
*/
function isClassName(className){
	var cuowu="rerror";
	if(cuowu==className) return true;
	return false;
}

//说明 ：用 Javascript 实现锚点(Anchor)间平滑跳转 
// 转换为数字
function intval(v)
{    
	 v = parseInt(v);    
	 return isNaN(v) ? 0 : v;
} 
// 获取元素信息
function getPos(e)
{    
	var l = 0;    
	var t  = 0;    
	var w = intval(e.style.width);    
	var h = intval(e.style.height);    
	var wb = e.offsetWidth;    
	var hb = e.offsetHeight;    
	while (e.offsetParent)
	{       
		l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0);        
		t += e.offsetTop  + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0);        
		e = e.offsetParent;    
	}    
	l += e.offsetLeft + (e.currentStyle?intval(e.currentStyle.borderLeftWidth):0);    
	t  += e.offsetTop  + (e.currentStyle?intval(e.currentStyle.borderTopWidth):0);    
	return {x:l, y:t, w:w, h:h, wb:wb, hb:hb}; 
} 
// 获取滚动条信息
function getScroll() 
{    
	 var t=0, l=0, w=0, h=0;	 
	 if (document.documentElement && document.documentElement.scrollTop)
	 {        
		 t = document.documentElement.scrollTop;        
		 l = document.documentElement.scrollLeft;        
		 w = document.documentElement.scrollWidth;       
		 h = document.documentElement.scrollHeight;    
	 }
	 else if (document.body)
	 {        
		 t = document.body.scrollTop;        
		 l = document.body.scrollLeft;        
		 w = document.body.scrollWidth;        
		 h = document.body.scrollHeight;    
	 }    
	 return { t: t, l: l, w: w, h: h };
} 
// 锚点(Anchor)间平滑跳转
function GoAnchor(el, duration)
{    
	 /*if(typeof el != 'object')
	 {
		 el = document.getElementById(el);
	 }     
	 if(!el) return;*/   
	 
	 location.hash = el;
	 return;
	 
	 var z = this;    
	 z.el = el;    
	 z.p = getPos(el);    
	 z.s = getScroll();    
	 z.clear = function()
	 {
		 window.clearInterval(z.timer);z.timer=null;
	 };    
	 z.t=(new Date).getTime();     
	 z.step = function()
	 {        
		 var t = (new Date).getTime();        
		 var p = (t - z.t) / duration;        
		 if (t >= duration + z.t)
		 {            
			 z.clear();            
			 window.setTimeout(function(){z.scroll(z.p.y, z.p.x);},13);         
		 }
		 else {            
			 st = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.y-z.s.t) + z.s.t;            
			 sl = ((-Math.cos(p*Math.PI)/2) + 0.5) * (z.p.x-z.s.l) + z.s.l;            
			 z.scroll(st, sl);        
		 }    
	 };    
	 z.scroll = function (t, l){window.scrollTo(l, t);};    
	 z.timer = window.setInterval(function(){z.step();},13);
}


	/**
	 * 只能输入正整数
	 */
	function TextOnlyNum(e,pPageSize)
	{
		// 响应回车
   var key = window.event ? e.keyCode : e.which;
		if(!((key >= 48 && key <= 57)||(key >= 96 && key <= 105)||(key == 8))){
			e.returnValue=false;
			if(e.keyCode == 13){
				RespontEnter(10);
			}
		} 
	} 
	//相应页面输入，按回车
	function RespontEnter(pPageSize){
		var pagecount = parseInt(document.getElementById("h_pagecount").value);
		var pageindex = parseInt(document.getElementById("h_pageindex").value);
		if( pagecount > 0){
			//获取页数
			var currentpage = parseInt(document.getElementById("t_currentpage").value);
			//等于当前页
			if(currentpage == pageindex){
				document.getElementById("t_currentpage").value = pageindex;
				currentpage = pageindex;
				return;
			}
			//如果是0则改成1
			if(currentpage == 0){
				document.getElementById("t_currentpage").value = 1;
				currentpage = 1;
			}
			//最大页数
			if(currentpage >= pagecount){
				document.getElementById("t_currentpage").value = pagecount;
				currentpage = pagecount;
			}
			GoPage(currentpage,pPageSize);
		}else{
			document.getElementById("t_currentpage").value = 1;
		}
	}
	//将分转换为元
	function FenToYuan(pFen){
		if(IsEmpty(pFen)){
			return "";
		}
		var fen = parseInt(pFen);
		var yuan = fen/100;
		return toDecimal2(yuan);
	}
	
	//除
	function accDiv(arg1,arg2){ 
		var t1=0,t2=0,r1,r2; 
		try{t1=arg1.toString().split(".")[1].length}catch(e){} 
		try{t2=arg2.toString().split(".")[1].length}catch(e){} 
		with(Math){ 
			r1=Number(arg1.toString().replace(".","")) 
			r2=Number(arg2.toString().replace(".","")) 
			return (r1/r2)*pow(10,t2-t1); 
		} 
	}

	
	//元转换为分
	function accMul(arg1,arg2) { 
		var m=0,s1=arg1.toString(),s2=arg2.toString(); 
		try{m+=s1.split(".")[1].length}catch(e){}
		try{m+=s2.split(".")[1].length}catch(e){}
		return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m); 
	}
	
	/**
	 * 使用方法：
	 * 在input中添加：style="color:#888;" value="请输入您遇到的问题" onfocus="OnFocusFun(this,'请输入您遇到的问题')" onblur="OnBlurFun(this,'请输入您遇到的问题')"
	 */
	/**
	 * 输入框得到焦点时触发事件
	 */
	function OnFocusFun(element,elementvalue){
		if(element.value==elementvalue){
			element.value="";
			element.style.color="#333";
		}
	}
	
	var order_count = 0;
	//生成订单号
	function orderId(){
		var d = new XDate();
		order_count = order_count + 1;
		if(order_count == 1000){
			order_count = 0;
		}
		var orderId=d.toString('yyyyMMddHHmmssfff') + PadLeftZero(order_count,3);
		return orderId;
	}
	
	//制保留2位小数，如：2，会在2后面补上00.即2.00  
  function toDecimal2(x) {  
      var f = parseFloat(x);  
      if (isNaN(f)) {  
          return false;  
      }  
      var f = Math.round(x*100)/100;  
      var s = f.toString();  
      var rs = s.indexOf('.');  
      if (rs < 0) {  
          rs = s.length;  
          s += '.';  
      }  
      while (s.length <= rs + 2) {  
          s += '0';  
      }  
      return s;  
  } 

///////////////////////////////////////////////////////jsdate.js/////////////////////////////////////////////////////////	
	
  /**
   * Description:
   * 
   * @author Gaven zhongjiawei2010@foxmail.com
   * @since 2012-5-10
   */
  var cal;
  var isFocus=false; //是否为焦点
  function SelectDate(obj,strFormat)
  {
      var date = new Date();
      var by = date.getFullYear()-80;  //最小值 → 80 年前
      var ey = date.getFullYear()+1;  //最大值 → 50 年后
      //cal = new Calendar(by, ey,1,strFormat);    //初始化英文版，0 为中文版
      cal = (cal==null) ? new Calendar(by, ey, 0) : cal;    //不用每次都初始化
      cal.dateFormatStyle = strFormat;
      cal.show(obj);
  }
  /**
  * 返回日期
  * @param d the delimiter
  * @param p the pattern of your date
  * 修改为根据用户指定的 style 来确定；
  */
  //String.prototype.toDate = function(x, p) {
  String.prototype.toDate = function(style) {
  /**
    if(x == null) x = "-";
    if(p == null) p = "ymd";
    var a = this.split(x);
    var y = parseInt(a[p.indexOf("y")]);
    //remember to change this next century ;)
    if(y.toString().length <= 2) y += 2000;
    if(isNaN(y)) y = new Date().getFullYear();
    var m = parseInt(a[p.indexOf("m")]) - 1;
    var d = parseInt(a[p.indexOf("d")]);
    if(isNaN(d)) d = 1;
    return new Date(y, m, d);
    */
    var y = this.substring(style.indexOf('y'),style.lastIndexOf('y')+1);//年
    var m = this.substring(style.indexOf('M'),style.lastIndexOf('M')+1);//月
    var d = this.substring(style.indexOf('d'),style.lastIndexOf('d')+1);//日
    if(isNaN(y)) y = new Date().getFullYear();
    if(isNaN(m)) m = new Date().getMonth();
    if(isNaN(d)) d = new Date().getDate();
    var dt ;
    eval ("dt = new Date('"+ y+"', '"+(m-1)+"','"+ d +"')");
    return dt;
  };

  /**
  * 格式化日期
  * @param   d the delimiter
  * @param   p the pattern of your date
  * @author  meizz
  */
  Date.prototype.format = function(style) {
    var o = {
      "M+" : this.getMonth() + 1, //month
      "d+" : this.getDate(),      //day
      "h+" : this.getHours(),     //hour
      "m+" : this.getMinutes(),   //minute
      "s+" : this.getSeconds(),   //second
      "w+" : "天一二三四五六".charAt(this.getDay()),   //week
      "q+" : Math.floor((this.getMonth() + 3) / 3),  //quarter
      "S"  : this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(style)) {
      style = style.replace(RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for(var k in o){
      if(new RegExp("("+ k +")").test(style)){
        style = style.replace(RegExp.$1,
          RegExp.$1.length == 1 ? o[k] :
          ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return style;
  };

  /**
  * 日历类
  * @param   beginYear 1990
  * @param   endYear   2010
  * @param   lang      0(中文)|1(英语) 可自由扩充
  * @param   dateFormatStyle  "yyyy-MM-dd";
  * @version 2006-04-01
  * @author  KimSoft (jinqinghua [at] gmail.com)
  * @update
  */
  function Calendar(beginYear, endYear, lang, dateFormatStyle) {
    this.beginYear = 1990;
    this.endYear = 2010;
    this.lang = 0;            //0(中文) | 1(英文)
    this.dateFormatStyle = "yyyy-MM-dd";

    if (beginYear != null && endYear != null){
      this.beginYear = beginYear;
      this.endYear = endYear;
    }
    if (lang != null){
      this.lang = lang;
    }

    if (dateFormatStyle != null){
      this.dateFormatStyle = dateFormatStyle;
    }

    this.dateControl = null;
    this.panel = this.getElementById("calendarPanel");
    this.container = this.getElementById("ContainerPanel");
    this.form  = null;

    this.date = new Date();
    this.year = this.date.getFullYear();
    this.month = this.date.getMonth();


    this.colors = {
    "cur_word"      : "#FFFFFF",  //当日日期文字颜色
    "cur_bg"        : "#00FF00",  //当日日期单元格背影色
    "sel_bg"        : "#FFCCCC",  //已被选择的日期单元格背影色
    "sun_word"      : "#FF0000",  //星期天文字颜色
    "sat_word"      : "#0000FF",  //星期六文字颜色
    "td_word_light" : "#333333",  //单元格文字颜色
    "td_word_dark"  : "#CCCCCC",  //单元格文字暗色
    "td_bg_out"     : "#EFEFEF",  //单元格背影色
    "td_bg_over"    : "#FFCC00",  //单元格背影色
    "tr_word"       : "#FFFFFF",  //日历头文字颜色
    "tr_bg"         : "#666666",  //日历头背影色
    "input_border"  : "#CCCCCC",  //input控件的边框颜色
    "input_bg"      : "#EFEFEF"   //input控件的背影色
    };

    this.draw();
    this.bindYear();
    this.bindMonth();
    //this.changeSelect();
    //this.bindData();
  }

  /**
  * 日历类属性（语言包，可自由扩展）
  */
  Calendar.language = {
    "year"   : [[""], [""]],
    "months" : [["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
          ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"]
           ],
    "weeks"  : [["日","一","二","三","四","五","六"],
          ["SUN","MON","TUR","WED","THU","FRI","SAT"]
           ],
    "clear"  : [["清空"], ["CLS"]],
    "today"  : [["今天"], ["TODAY"]],
    "close"  : [["关闭"], ["CLOSE"]]
  };

  Calendar.prototype.draw = function() {
    calendar = this;

    var mvAry = [];
    //mvAry[mvAry.length]  = '  <form name="calendarForm" style="margin: 0px;">'; //因 <form> 不能嵌套
    mvAry[mvAry.length]  = '  <div name="calendarForm" style="margin: 0px;">';
    mvAry[mvAry.length]  = '    <table width="100%" border="0" cellpadding="0" cellspacing="1">';
    mvAry[mvAry.length]  = '      <tr>';
    mvAry[mvAry.length]  = '        <th align="left" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="prevMonth" type="button" id="prevMonth" value="&lt;" /></th>';
    mvAry[mvAry.length]  = '        <th align="center" width="98%" nowrap="nowrap"><select name="calendarYear" id="calendarYear" style="font-size:12px;"></select><select name="calendarMonth" id="calendarMonth" style="font-size:12px;"></select></th>';
    mvAry[mvAry.length]  = '        <th align="right" width="1%"><input style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:16px;height:20px;" name="nextMonth" type="button" id="nextMonth" value="&gt;" /></th>';
    mvAry[mvAry.length]  = '      </tr>';
    mvAry[mvAry.length]  = '    </table>';
    mvAry[mvAry.length]  = '    <table id="calendarTable" width="100%" style="border:0px solid #CCCCCC;background-color:#FFFFFF" border="0" cellpadding="3" cellspacing="1">';
    mvAry[mvAry.length]  = '      <tr>';
    for(var i = 0; i < 7; i++) {
      mvAry[mvAry.length]  = '      <th style="font-weight:normal;background-color:' + calendar.colors["tr_bg"] + ';color:' + calendar.colors["tr_word"] + ';">' + Calendar.language["weeks"][this.lang][i] + '</th>';
    }
    mvAry[mvAry.length]  = '      </tr>';
    for(var i = 0; i < 6;i++){
      mvAry[mvAry.length]  = '    <tr align="center">';
      for(var j = 0; j < 7; j++) {
        if (j == 0){
          mvAry[mvAry.length]  = '  <td style="cursor:default;color:' + calendar.colors["sun_word"] + ';"></td>';
        } else if(j == 6) {
          mvAry[mvAry.length]  = '  <td style="cursor:default;color:' + calendar.colors["sat_word"] + ';"></td>';
        } else {
          mvAry[mvAry.length]  = '  <td style="cursor:default;"></td>';
        }
      }
      mvAry[mvAry.length]  = '    </tr>';
    }
    mvAry[mvAry.length]  = '      <tr style="background-color:' + calendar.colors["input_bg"] + ';">';
    mvAry[mvAry.length]  = '        <th colspan="2"><input name="calendarClear" type="button" id="calendarClear" value="' + Calendar.language["clear"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
    mvAry[mvAry.length]  = '        <th colspan="3"><input name="calendarToday" type="button" id="calendarToday" value="' + Calendar.language["today"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
    mvAry[mvAry.length]  = '        <th colspan="2"><input name="calendarClose" type="button" id="calendarClose" value="' + Calendar.language["close"][this.lang] + '" style="border: 1px solid ' + calendar.colors["input_border"] + ';background-color:' + calendar.colors["input_bg"] + ';width:100%;height:20px;font-size:12px;"/></th>';
    mvAry[mvAry.length]  = '      </tr>';
    mvAry[mvAry.length]  = '    </table>';
    //mvAry[mvAry.length]  = '  </from>';
    mvAry[mvAry.length]  = '  </div>';
    this.panel.innerHTML = mvAry.join("");
    

    var obj = this.getElementById("prevMonth");
    obj.onclick = function () {calendar.goPrevMonth(calendar);};
    obj.onblur = function () {calendar.onblur();};
    this.prevMonth= obj;
    
    obj = this.getElementById("nextMonth");
    obj.onclick = function () {calendar.goNextMonth(calendar);};
    obj.onblur = function () {calendar.onblur();};
    this.nextMonth= obj;

  obj = this.getElementById("calendarClear");
    obj.onclick = function () {calendar.dateControl.value = "";calendar.hide();};
    this.calendarClear = obj;
    
    obj = this.getElementById("calendarClose");
    obj.onclick = function () {calendar.hide();};
    this.calendarClose = obj;
    
    obj = this.getElementById("calendarYear");
    obj.onchange = function () {calendar.update(calendar);};
    obj.onblur = function () {calendar.onblur();};
    this.calendarYear = obj;
    
    obj = this.getElementById("calendarMonth");
    with(obj)
    {
      onchange = function () {calendar.update(calendar);};
      onblur = function () {calendar.onblur();};
    }this.calendarMonth = obj;

    obj = this.getElementById("calendarToday");
    obj.onclick = function () {
      var today = new Date();
      /**//*calendar.date = today;
      calendar.year = today.getFullYear();
      calendar.month = today.getMonth();
      calendar.changeSelect();
      calendar.bindData();
      */ 
      calendar.dateControl.value = today.format(calendar.dateFormatStyle);
      calendar.hide();
    };
    this.calendarToday = obj;

  };

  //年份下拉框绑定数据
  Calendar.prototype.bindYear = function() {
    //var cy = this.form.calendarYear;
    var cy = this.calendarYear;
    cy.length = 0;
    for (var i = this.beginYear; i <= this.endYear; i++){
      cy.options[cy.length] = new Option(i + Calendar.language["year"][this.lang], i);
    }
  };

  //月份下拉框绑定数据
  Calendar.prototype.bindMonth = function() {
    //var cm = this.form.calendarMonth;
    var cm = this.calendarMonth;
    cm.length = 0;
    for (var i = 0; i < 12; i++){
      cm.options[cm.length] = new Option(Calendar.language["months"][this.lang][i], i);
    }
  };

  //向前一月
  Calendar.prototype.goPrevMonth = function(e){
    if (this.year == this.beginYear && this.month == 0){return;}
    this.month--;
    if (this.month == -1) {
      this.year--;
      this.month = 11;
    }
    this.date = new Date(this.year, this.month, 1);
    this.changeSelect();
    this.bindData();
  };

  //向后一月
  Calendar.prototype.goNextMonth = function(e){
    if (this.year == this.endYear && this.month == 11){return;}
    this.month++;
    if (this.month == 12) {
      this.year++;
      this.month = 0;
    }
    this.date = new Date(this.year, this.month, 1);
    this.changeSelect();
    this.bindData();
  };

  //改变SELECT选中状态
  Calendar.prototype.changeSelect = function() {
    var cy = this.calendarYear;
    var cm = this.calendarMonth;
  //减少运算次数
    cy[this.date.getFullYear()-this.beginYear].selected = true;
    cm[this.date.getMonth()].selected =true;
  /**
    for (var i= 0; i < cy.length; i++){
      if (cy.options[i].value == this.date.getFullYear()){
        cy[i].selected = true;
        break;
      }
    }
    for (var i= 0; i < cm.length; i++){
      if (cm.options[i].value == this.date.getMonth()){
        cm[i].selected = true;
        break;
      }
    }
  */

  };

  //更新年、月
  Calendar.prototype.update = function (e){
    this.year  = e.calendarYear.options[e.calendarYear.selectedIndex].value;
    this.month = e.calendarMonth.options[e.calendarMonth.selectedIndex].value;
    this.date = new Date(this.year, this.month, 1);
    this.changeSelect();
    this.bindData();
  };

  //绑定数据到月视图
  Calendar.prototype.bindData = function () {
    var calendar = this;
  // var dateArray = this.getMonthViewArray(this.date.getYear(), this.date.getMonth());
    var dateArray = this.getMonthViewArray(this.date.getFullYear(), this.date.getMonth());
  var tds = this.getElementById("calendarTable").getElementsByTagName("td");
    for(var i = 0; i < tds.length; i++) {
    //tds[i].style.color = calendar.colors["td_word_light"];
    tds[i].style.backgroundColor = calendar.colors["td_bg_out"];
      tds[i].onclick = function () {return;};
      tds[i].onmouseover = function () {return;};
      tds[i].onmouseout = function () {return;};
      if (i > dateArray.length - 1) break;
      tds[i].innerHTML = dateArray[i];
      if (dateArray[i] != "&nbsp;"&&new Date().format(calendar.dateFormatStyle) >=
            new Date(calendar.date.getFullYear(),
                     calendar.date.getMonth(),
                     dateArray[i]).format(calendar.dateFormatStyle)){
        tds[i].onclick = function () {
          if (calendar.dateControl != null){
            calendar.dateControl.value = new Date(calendar.date.getFullYear(),
                                                  calendar.date.getMonth(),
                                                  this.innerHTML).format(calendar.dateFormatStyle);
          }
          calendar.hide();
        };
        tds[i].onmouseover = function () {
          this.style.backgroundColor = calendar.colors["td_bg_over"];
        };
        tds[i].onmouseout = function () {
          this.style.backgroundColor = calendar.colors["td_bg_out"];
        };
        
        if (new Date().format(calendar.dateFormatStyle) ==
            new Date(calendar.date.getFullYear(),
                     calendar.date.getMonth(),
                     dateArray[i]).format(calendar.dateFormatStyle)) {
          //tds[i].style.color = calendar.colors["cur_word"];
          tds[i].style.backgroundColor = calendar.colors["cur_bg"];
          tds[i].onmouseover = function () {
            this.style.backgroundColor = calendar.colors["td_bg_over"];
          };
          tds[i].onmouseout = function () {
            this.style.backgroundColor = calendar.colors["cur_bg"];
          };
          //continue; //若不想当天单元格的背景被下面的覆盖，请取消注释
        }//end if
        
        //设置已被选择的日期单元格背影色 
        if (calendar.dateControl != null && calendar.dateControl.value == new Date(calendar.date.getFullYear(),
                     calendar.date.getMonth(),
                     dateArray[i]).format(calendar.dateFormatStyle)) {
          tds[i].style.backgroundColor = calendar.colors["sel_bg"];
          tds[i].onmouseover = function () {
            this.style.backgroundColor = calendar.colors["td_bg_over"];
          };
          tds[i].onmouseout = function () {
            this.style.backgroundColor = calendar.colors["sel_bg"];
          };
        }
      }
    }
  };

  //根据年、月得到月视图数据(数组形式)
  Calendar.prototype.getMonthViewArray = function (y, m) {
    var mvArray = [];
    var dayOfFirstDay = new Date(y, m, 1).getDay();
    var daysOfMonth = new Date(y, m + 1, 0).getDate();
    for (var i = 0; i < 42; i++) {
      mvArray[i] = "&nbsp;";
    }
    for (var i = 0; i < daysOfMonth; i++){
      mvArray[i + dayOfFirstDay] = i + 1;
    }
    return mvArray;
  };

  //扩展 document.getElementById(id) 多浏览器兼容性 from meizz tree source
  Calendar.prototype.getElementById = function(id){
    if (typeof(id) != "string" || id == "") return null;
    if (document.getElementById) return document.getElementById(id);
    if (document.all) return document.all(id);
    try {return eval(id);} catch(e){ return null;}
  };

  //扩展 object.getElementsByTagName(tagName)
  Calendar.prototype.getElementsByTagName = function(object, tagName){
    if (document.getElementsByTagName) return document.getElementsByTagName(tagName);
    if (document.all) return document.all.tags(tagName);
  };

  //取得HTML控件绝对位置
  Calendar.prototype.getAbsPoint = function (e){
    var x = e.offsetLeft;
    var y = e.offsetTop;
    while(e = e.offsetParent){
      x += e.offsetLeft;
      y += e.offsetTop;
    }
    return {"x": x, "y": y};
  };

  //显示日历
  Calendar.prototype.show = function (dateObj, popControl) {
    if (dateObj == null){
      throw new Error("arguments[0] is necessary");
    }
    this.dateControl = dateObj;
    
    //if (dateObj.value.length > 0){
    //this.date = new Date(dateObj.value.toDate());
    //this.date = new Date(dateObj.value.toDate(this.dateFormatStyle));//带入用户指定的 style  
    this.date = (dateObj.value.length > 0) ? new Date(dateObj.value.toDate(this.dateFormatStyle)) : new Date() ;//若为空则显示当前月份
    this.year = this.date.getFullYear();
    this.month = this.date.getMonth();
    this.changeSelect();
    this.bindData();
    //}
    if (popControl == null){
      popControl = dateObj;
    }
    var xy = this.getAbsPoint(popControl);
    this.panel.style.left = xy.x -25 + "px";
    this.panel.style.top = (xy.y + dateObj.offsetHeight) + "px";
    
    //把 visibility 变为 display，并添加失去焦点的事件
    //this.setDisplayStyle("select", "hidden");
    //this.panel.style.visibility = "visible";
    //this.container.style.visibility = "visible";
    this.panel.style.display = "";
    this.container.style.display = "";
    
    dateObj.onblur = function(){calendar.onblur();};
    this.container.onmouseover = function(){isFocus=true;};
    this.container.onmouseout = function(){isFocus=false;};
  };

  //隐藏日历
  Calendar.prototype.hide = function() {
    //this.setDisplayStyle("select", "visible");
    //this.panel.style.visibility = "hidden";
    //this.container.style.visibility = "hidden";
    this.panel.style.display = "none";
    this.container.style.display = "none";
    isFocus=false;
  };

  //焦点转移时隐藏日历 
  Calendar.prototype.onblur = function() {
      if(!isFocus){this.hide();}
  };

  //用<iframe> 遮住 IE 的下拉框
  /**
  //设置控件显示或隐藏
  Calendar.prototype.setDisplayStyle = function(tagName, style) {
    var tags = this.getElementsByTagName(null, tagName)
    for(var i = 0; i < tags.length; i++) {
      if (tagName.toLowerCase() == "select" &&
         (tags[i].name == "calendarYear" ||
        tags[i].name == "calendarMonth")){
        continue;
      }
      //tags[i].style.visibility = style;
      tags[i].style.display = style;
    }
  }
  */
  //document.write('<div id="ContainerPanel" style="visibility:hidden"><div id="calendarPanel" style="position: absolute;visibility: hidden;z-index: 9999;');
  document.write('<div id="ContainerPanel" style="display:none;"><div id="calendarPanel" style="position: absolute;display: none;z-index: 9999;');
  document.write('background-color: #FFFFFF;border: 1px solid #CCCCCC;width:175px;font-size:12px;"></div>');
  if(document.all)
  {
  //bryan hide 20120523
  /*document.write('<iframe style="position:absolute;z-index:2000;width:expression(this.previousSibling.offsetWidth);');
  document.write('height:expression(this.previousSibling.offsetHeight);');
  document.write('left:expression(this.previousSibling.offsetLeft);top:expression(this.previousSibling.offsetTop);');
  document.write('display:expression(this.previousSibling.style.display);" scrolling="no" frameborder="no"></iframe>');*/
  }
  document.write('</div>');
  //var calendar = new Calendar();  //此句要注释，否则 IE 将报错
  //调用calendar.show(dateControl, popControl);
	
///////////////////////////////////////////////////////json2.js/////////////////////////////////////////////////////////	
	
  /*
  http://www.JSON.org/json2.js
  2008-05-25

  Public Domain.

  NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

  See http://www.JSON.org/js.html

  This file creates a global JSON object containing two methods: stringify
  and parse.

      JSON.stringify(value, replacer, space)
          value       any JavaScript value, usually an object or array.

          replacer    an optional parameter that determines how object
                      values are stringified for objects without a toJSON
                      method. It can be a function or an array.

          space       an optional parameter that specifies the indentation
                      of nested structures. If it is omitted, the text will
                      be packed without extra whitespace. If it is a number,
                      it will specify the number of spaces to indent at each
                      level. If it is a string (such as '\t' or '&nbsp;'),
                      it contains the characters used to indent at each level.

          This method produces a JSON text from a JavaScript value.

          When an object value is found, if the object contains a toJSON
          method, its toJSON method will be called and the result will be
          stringified. A toJSON method does not serialize: it returns the
          value represented by the name/value pair that should be serialized,
          or undefined if nothing should be serialized. The toJSON method
          will be passed the key associated with the value, and this will be
          bound to the object holding the key.

          For example, this would serialize Dates as ISO strings.

              Date.prototype.toJSON = function (key) {
                  function f(n) {
                      // Format integers to have at least two digits.
                      return n < 10 ? '0' + n : n;
                  }

                  return this.getUTCFullYear()   + '-' +
                       f(this.getUTCMonth() + 1) + '-' +
                       f(this.getUTCDate())      + 'T' +
                       f(this.getUTCHours())     + ':' +
                       f(this.getUTCMinutes())   + ':' +
                       f(this.getUTCSeconds())   + 'Z';
              };

          You can provide an optional replacer method. It will be passed the
          key and value of each member, with this bound to the containing
          object. The value that is returned from your method will be
          serialized. If your method returns undefined, then the member will
          be excluded from the serialization.

          If the replacer parameter is an array, then it will be used to
          select the members to be serialized. It filters the results such
          that only members with keys listed in the replacer array are
          stringified.

          Values that do not have JSON representations, such as undefined or
          functions, will not be serialized. Such values in objects will be
          dropped; in arrays they will be replaced with null. You can use
          a replacer function to replace those with JSON values.
          JSON.stringify(undefined) returns undefined.

          The optional space parameter produces a stringification of the
          value that is filled with line breaks and indentation to make it
          easier to read.

          If the space parameter is a non-empty string, then that string will
          be used for indentation. If the space parameter is a number, then
          the indentation will be that many spaces.

          Example:

          text = JSON.stringify(['e', {pluribus: 'unum'}]);
          // text is '["e",{"pluribus":"unum"}]'


          text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
          // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

          text = JSON.stringify([new Date()], function (key, value) {
              return this[key] instanceof Date ?
                  'Date(' + this[key] + ')' : value;
          });
          // text is '["Date(---current time---)"]'


      JSON.parse(text, reviver)
          This method parses a JSON text to produce an object or array.
          It can throw a SyntaxError exception.

          The optional reviver parameter is a function that can filter and
          transform the results. It receives each of the keys and values,
          and its return value is used instead of the original value.
          If it returns what it received, then the structure is not modified.
          If it returns undefined then the member is deleted.

          Example:

          // Parse the text. Values that look like ISO date strings will
          // be converted to Date objects.

          myData = JSON.parse(text, function (key, value) {
              var a;
              if (typeof value === 'string') {
                  a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                  if (a) {
                      return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                          +a[5], +a[6]));
                  }
              }
              return value;
          });

          myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
              var d;
              if (typeof value === 'string' &&
                      value.slice(0, 5) === 'Date(' &&
                      value.slice(-1) === ')') {
                  d = new Date(value.slice(5, -1));
                  if (d) {
                      return d;
                  }
              }
              return value;
          });


  This is a reference implementation. You are free to copy, modify, or
  redistribute.

  This code should be minified before deployment.
  See http://javascript.crockford.com/jsmin.html

  USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
  NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
  charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
  getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
  parse, propertyIsEnumerable, prototype, push, replace, slice, stringify,
  test, toJSON, toString
*/

if (!this.JSON) {

//Create a JSON object only if one does not already exist. We create the
//object in a closure to avoid creating global variables.

  JSON = function () {

      function f(n) {
          // Format integers to have at least two digits.
          return n < 10 ? '0' + n : n;
      }

      Date.prototype.toJSON = function (key) {

          return this.getUTCFullYear()   + '-' +
               f(this.getUTCMonth() + 1) + '-' +
               f(this.getUTCDate())      + 'T' +
               f(this.getUTCHours())     + ':' +
               f(this.getUTCMinutes())   + ':' +
               f(this.getUTCSeconds())   + 'Z';
      };

      var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
          escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
          gap,
          indent,
          meta = {    // table of character substitutions
              '\b': '\\b',
              '\t': '\\t',
              '\n': '\\n',
              '\f': '\\f',
              '\r': '\\r',
              '"' : '\\"',
              '\\': '\\\\'
          },
          rep;


      function quote(string) {

//If the string contains no control characters, no quote characters, and no
//backslash characters, then we can safely slap some quotes around it.
//Otherwise we must also replace the offending characters with safe escape
//sequences.

          escapeable.lastIndex = 0;
          return escapeable.test(string) ?
              '"' + string.replace(escapeable, function (a) {
                  var c = meta[a];
                  if (typeof c === 'string') {
                      return c;
                  }
                  return '\\u' + ('0000' +
                          (+(a.charCodeAt(0))).toString(16)).slice(-4);
              }) + '"' :
              '"' + string + '"';
      }


      function str(key, holder) {

//Produce a string from holder[key].

          var i,          // The loop counter.
              k,          // The member key.
              v,          // The member value.
              length,
              mind = gap,
              partial,
              value = holder[key];

//If the value has a toJSON method, call it to obtain a replacement value.

          if (value && typeof value === 'object' &&
                  typeof value.toJSON === 'function') {
              value = value.toJSON(key);
          }

//If we were called with a replacer function, then call the replacer to
//obtain a replacement value.

          if (typeof rep === 'function') {
              value = rep.call(holder, key, value);
          }

//What happens next depends on the value's type.

          switch (typeof value) {
          case 'string':
              return quote(value);

          case 'number':

//JSON numbers must be finite. Encode non-finite numbers as null.

              return isFinite(value) ? String(value) : 'null';

          case 'boolean':
          case 'null':

//If the value is a boolean or null, convert it to a string. Note:
//typeof null does not produce 'null'. The case is included here in
//the remote chance that this gets fixed someday.

              return String(value);

//If the type is 'object', we might be dealing with an object or an array or
//null.

          case 'object':

//Due to a specification blunder in ECMAScript, typeof null is 'object',
//so watch out for that case.

              if (!value) {
                  return 'null';
              }

//Make an array to hold the partial results of stringifying this object value.

              gap += indent;
              partial = [];

//If the object has a dontEnum length property, we'll treat it as an array.

              if (typeof value.length === 'number' &&
                      !(value.propertyIsEnumerable('length'))) {

//The object is an array. Stringify every element. Use null as a placeholder
//for non-JSON values.

                  length = value.length;
                  for (i = 0; i < length; i += 1) {
                      partial[i] = str(i, value) || 'null';
                  }

//Join all of the elements together, separated with commas, and wrap them in
//brackets.

                  v = partial.length === 0 ? '[]' :
                      gap ? '[\n' + gap +
                              partial.join(',\n' + gap) + '\n' +
                                  mind + ']' :
                            '[' + partial.join(',') + ']';
                  gap = mind;
                  return v;
              }

//If the replacer is an array, use it to select the members to be stringified.

              if (rep && typeof rep === 'object') {
                  length = rep.length;
                  for (i = 0; i < length; i += 1) {
                      k = rep[i];
                      if (typeof k === 'string') {
                          v = str(k, value, rep);
                          if (v) {
                              partial.push(quote(k) + (gap ? ': ' : ':') + v);
                          }
                      }
                  }
              } else {

//Otherwise, iterate through all of the keys in the object.

                  for (k in value) {
                      if (Object.hasOwnProperty.call(value, k)) {
                          v = str(k, value, rep);
                          if (v) {
                              partial.push(quote(k) + (gap ? ': ' : ':') + v);
                          }
                      }
                  }
              }

//Join all of the member texts together, separated with commas,
//and wrap them in braces.

              v = partial.length === 0 ? '{}' :
                  gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                          mind + '}' : '{' + partial.join(',') + '}';
              gap = mind;
              return v;
          }
      }

//Return the JSON object containing the stringify and parse methods.

      return {
          stringify: function (value, replacer, space) {

//The stringify method takes a value and an optional replacer, and an optional
//space parameter, and returns a JSON text. The replacer can be a function
//that can replace values, or an array of strings that will select the keys.
//A default replacer method can be provided. Use of the space parameter can
//produce text that is more easily readable.

              var i;
              gap = '';
              indent = '';

//If the space parameter is a number, make an indent string containing that
//many spaces.

              if (typeof space === 'number') {
                  for (i = 0; i < space; i += 1) {
                      indent += ' ';
                  }

//If the space parameter is a string, it will be used as the indent string.

              } else if (typeof space === 'string') {
                  indent = space;
              }

//If there is a replacer, it must be a function or an array.
//Otherwise, throw an error.

              rep = replacer;
              if (replacer && typeof replacer !== 'function' &&
                      (typeof replacer !== 'object' ||
                       typeof replacer.length !== 'number')) {
                  throw new Error('JSON.stringify');
              }

//Make a fake root object containing our value under the key of ''.
//Return the result of stringifying the value.

              return str('', {'': value});
          },


          parse: function (text, reviver) {

//The parse method takes a text and an optional reviver function, and returns
//a JavaScript value if the text is a valid JSON text.

              var j;

              function walk(holder, key) {

//The walk method is used to recursively walk the resulting structure so
//that modifications can be made.

                  var k, v, value = holder[key];
                  if (value && typeof value === 'object') {
                      for (k in value) {
                          if (Object.hasOwnProperty.call(value, k)) {
                              v = walk(value, k);
                              if (v !== undefined) {
                                  value[k] = v;
                              } else {
                                  delete value[k];
                              }
                          }
                      }
                  }
                  return reviver.call(holder, key, value);
              }


//Parsing happens in four stages. In the first stage, we replace certain
//Unicode characters with escape sequences. JavaScript handles many characters
//incorrectly, either silently deleting them, or treating them as line endings.

              cx.lastIndex = 0;
              if (cx.test(text)) {
                  text = text.replace(cx, function (a) {
                      return '\\u' + ('0000' +
                              (+(a.charCodeAt(0))).toString(16)).slice(-4);
                  });
              }

//In the second stage, we run the text against regular expressions that look
//for non-JSON patterns. We are especially concerned with '()' and 'new'
//because they can cause invocation, and '=' because it can cause mutation.
//But just to be safe, we want to reject all unexpected forms.

//We split the second stage into 4 regexp operations in order to work around
//crippling inefficiencies in IE's and Safari's regexp engines. First we
//replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
//replace all simple value tokens with ']' characters. Third, we delete all
//open brackets that follow a colon or comma or that begin the text. Finally,
//we look to see that the remaining characters are only whitespace or ']' or
//',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

              if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

//In the third stage we use the eval function to compile the text into a
//JavaScript structure. The '{' operator is subject to a syntactic ambiguity
//in JavaScript: it can begin a block or an object literal. We wrap the text
//in parens to eliminate the ambiguity.

                  j = eval('(' + text + ')');

//In the optional fourth stage, we recursively walk the new structure, passing
//each name/value pair to a reviver function for possible transformation.

                  return typeof reviver === 'function' ?
                      walk({'': j}, '') : j;
              }

//If the text is not JSON parseable, then a SyntaxError is thrown.

              throw new SyntaxError('JSON.parse');
          }
      };
  }();
}
	
///////////////////////////////////////////////////////end/////////////////////////////////////////////////////////		
	
	
